﻿using EasyService;
using EasyTask.EasyHelper;
using Quartz;
using System.Threading.Tasks;

namespace EasyTask.EasyCore
{
    /// <summary>
    /// EasyJob检测器
    /// </summary>
    class MonitorJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {
            var ts = new TaskService();
            var tasks = await ts.GetAllTasksAsync();

            foreach (var item in tasks)
            {
                var type = ServiceAutoFac.GetAssemlyJobs(item.JobName);
                if (type != null)
                {

                    switch (item.ServiceState)
                    {
                        case EasyEnum.ServiceState.PrepareStart:
                            await QuartzManager.AddJobAsync(type, item.JobName, item.JobGroupName, item.JobTriggerName, item.JobTriggerGroupName, item.Cron);
                            await ts.UpdateTaskAsync(item.JobName, EasyEnum.ServiceState.Started);
                            break;
                        case EasyEnum.ServiceState.PrepareStop:
                            await QuartzManager.RemoveJobAsync(item.JobName, item.JobGroupName);
                            await ts.UpdateTaskAsync(item.JobName, EasyEnum.ServiceState.Stoped);
                            break;
                        case EasyEnum.ServiceState.PreparePasue:
                            await QuartzManager.PauseJobAsync(item.JobName, item.JobGroupName);
                            await ts.UpdateTaskAsync(item.JobName, EasyEnum.ServiceState.Paused);
                            break;
                        case EasyEnum.ServiceState.PrepareUpdate:
                            await QuartzManager.UpdateJobAsync(item.JobName, item.JobGroupName, item.JobTriggerName, item.JobTriggerGroupName, item.Cron);
                            await ts.UpdateTaskAsync(item.JobName, EasyEnum.ServiceState.Started);
                            break;
                        /*
                         以下状态不做处理
                        case EasyEnum.ServiceState.Started: break;
                        case EasyEnum.ServiceState.Stoped: break;
                        case EasyEnum.ServiceState.Paused: break;
                        case EasyEnum.ServiceState.ManualStoped: break;
                        case EasyEnum.ServiceState.Unknow: break;
                        case EasyEnum.ServiceState.Invalid: break;
                        */
                        default:
                            break;
                    }
                }
            }
        }
    }
}
